<script>
import { merge, forEach, cloneDeep } from 'lodash-es';
import { rulesPattern } from '@/utils/tools.js';
import { getToken } from '@/utils/auth';
import { useGlobalState } from '@/store/globalState.js';
import { getBranchType, provinceList, citysList, addEnterprise, editEnterprise, getDownloadPath } from '@/api/index.js';
export default {
  props: {
    isEdit: { type: Boolean, default: false },
    title: { type: String, default: () => '' },
    cancel: { type: Boolean, default: false },
    submit: { type: Number, default: 0 },
    infoData: { type: Object, default: () => null },
  },
  data() {
    return {
      formParams: {
        enterpriseImage: null,
        enterpriseName: null,
        uscc: null,
        enterpriseViewId: null,
        entrustType: null,
        introduce: null,
        province: null,
        city: null,
        county: null,
        lon: null,
        lat: null,
        address: null,
        responsiblePerson: null,
        contactPhone: null,
        gaugesList: [], //户号信息
      },
      rules: {
        enterpriseImage: [
          {
            required: true,
            message: '请上传机构展示图',
            trigger: ['blur', 'change'],
          },
        ],
        enterpriseName: [{ required: true, message: '请输入机构名称', trigger: ['blur', 'change'] }],
        uscc: [{ required: true, message: '请输入统一社会信用代码', trigger: ['blur', 'change'] }],
        enterpriseViewId: [{ required: false, message: '请输入机构组织代码', trigger: ['blur', 'change'] }],
        entrustType: [{ required: true, message: '请选择机构类型', trigger: 'change' }],
        introduce: [{ required: true, message: '请输入机构介绍', trigger: ['blur', 'change'] }],
        province: [{ required: true, message: '请选择省', trigger: 'change' }],
        city: [{ required: true, message: '请选择市', trigger: 'change' }],
        county: [{ required: true, message: '请选择县', trigger: 'change' }],
        lon: [{ required: true, message: '请输入经度', trigger: 'blur' }],
        lat: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        responsiblePerson: [{ required: false, message: '请输入', trigger: 'blur' }],
        contactPhone: [
          { required: false, message: '请输入', trigger: 'blur' },
          { max: 15, message: '最长不超过15位', trigger: 'blur' },
        ],
      },
      AccountList: [
        {
          gaugesName: '',
          gaugesNum: '',
        },
      ],
      accountRules: {
        gaugesName: { required: true, message: '请输入户号名称', trigger: ['blur', 'change'] },
        gaugesNum: { required: true, message: '请输入户号编号', trigger: ['blur', 'change'] },
      },
      provinceList: [],
      cityList: [],
      countyList: [],
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: useGlobalState().globalState.fileUrl + '/file/uploadFile',
      },
      fileLists: [],
      enterpriseImage: '',
      dwlxLists: [],
      cityValue: null,
    };
  },
  watch: {
    cancel: {
      handler(n) {
        if (n) {
          this.resetForm('formParams');
          this.formParams.gaugesList = [];
          this.fileLists = [];
          this.enterpriseImage = '';
          this.formParams.province = '山西省';
          this.cityValue = null;
        }
      },
    },
    submit: {
      handler(n) {
        if (n > 0) {
          this.$refs.formParams.validate(valid => {
            if (valid) {
              let total = 0;
              if (this.$refs.accountForm?.length > 0) {
                for (let i = 0; i < this.$refs.accountForm.length; i++) {
                  this.$refs.accountForm[i].validate(valid => {
                    if (valid) {
                      total = total + 1;
                    } else {
                      return false;
                    }
                  });
                }
              }
              if (!this.$refs.accountForm || total === this.$refs.accountForm?.length) {
                if (this.title === '新增') {
                  this.$confirm(`请确认机构信息无误`, '提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning',
                  }).then(() => {
                    this.netAddEnterprise();
                  });
                } else if (this.title === '编辑') {
                  this.$confirm(`请确认机构信息无误`, '提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning',
                  }).then(() => {
                    this.netEditEnterprise();
                  });
                }
              }
            } else {
              return false;
            }
          });
        }
      },
    },
    infoData: {
      handler(n) {
        this.formParams = n?.enterprise ?? {};
        this.formParams.gaugesList = n?.gaugesList ?? [];
        forEach(this.cityList, el => {
          if (el.areaName === n?.enterprise?.city) {
            this.cityValue = el;
          }
        });
        getDownloadPath(n?.enterprise?.enterpriseImage).then(res => {
          console.log(res, 'getDownloadPath');
          this.fileLists = [
            {
              name: '',
              url: useGlobalState().globalState.fileUrl + res?.data?.url ?? '',
            },
          ];
        });
      },
    },
  },
  created() {
    this.getShengData();
    this.netGetBranchType();
  },
  methods: {
    netAddEnterprise() {
      addEnterprise({ enterprise: this.formParams, gaugesList: this.formParams.gaugesList }).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg);
          this.$emit('onSuccess');
        }
      });
    },
    netEditEnterprise() {
      editEnterprise({ enterprise: this.formParams, gaugesList: this.formParams.gaugesList }).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg);
          this.$emit('onSuccess');
        }
      });
    },
    //获取省数据
    getShengData() {
      provinceList().then(res => {
        this.provinceList = res.data;
        this.formParams.province = '山西省';
        this.getCityData();
      });
    },
    // provinceChange(val) {
    //   this.getCityData();
    //   this.editParams.areaCity = '';
    //   this.editParams.areaCounty = '';
    // },
    //获取市数据
    getCityData() {
      citysList({
        parentCode: '140000',
      }).then(res => {
        this.cityList = res.rows;
      });
    },
    citysChange(val) {
      this.formParams.city = val.areaName;
      this.getCountyData(val.areaCode);
      this.formParams.county = null;
    },
    //获取县区数据
    getCountyData(val) {
      citysList({
        parentCode: val,
      }).then(res => {
        this.countyList = res.rows;
      });
    },
    netGetBranchType() {
      getBranchType().then(res => {
        this.dwlxLists = res.data;
      });
    },
    handleAvatarSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.fileLists = fileList;
        this.enterpriseImage = response.data.url;
        this.formParams.enterpriseImage = response.data.url;
        this.$refs.formParams.validateField('enterpriseImage');
      } else {
        this.$message.error(response.msg);
        this.fileLists = [];
        this.enterpriseImage = '';
        this.formParams.enterpriseImage = null;
        this.$refs.formParams.validateField('enterpriseImage');
      }
    },
    handleRemove() {
      this.fileLists = [];
      this.enterpriseImage = '';
      this.formParams.enterpriseImage = null;
      this.$refs.formParams.validateField('enterpriseImage');
    },
    beforeAvatarUpload(file) {
      let types = ['image/gif', 'image/jpg', 'image/png', 'image/jpeg', 'image/pneg'];
      const isImage = types.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG、GIF、PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      return isImage && isLt2M;
    },
    handleExceed() {
      this.$message.warning('当前限制最大上传数量：1 ,上传新的文件之前请先删除原文件！');
    },
    addMeter() {
      let obj = cloneDeep(this.AccountList[0]);
      this.formParams.gaugesList.push(obj);
      this.$forceUpdate();
    },
    deleteMeter(index) {
      this.formParams.gaugesList.splice(index, 1);
      this.$forceUpdate();
    },
  },
};
</script>
<template>
  <el-form
    :model="formParams"
    :rules="isEdit ? rules : null"
    :inline="true"
    ref="formParams"
    size="small"
    class="queryForm u-base-fg"
    label-width="150px"
    :disabled="!isEdit"
  >
    <el-form-item class="u-df-spb u-w100 itemForm">
      <el-col :span="14">
        <el-form-item label="机构展示图" prop="enterpriseImage">
          <el-upload
            class="uploadPic"
            :action="upload.url"
            list-type="picture-card"
            :limit="1"
            name="file"
            :show-file-list="true"
            :headers="upload.headers"
            :before-upload="beforeAvatarUpload"
            :on-exceed="handleExceed"
            :file-list="fileLists"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove"
            :class="{ styleA: fileLists.length === 0, styleB: fileLists.length === 1 }"
          >
            <i class="el-icon-plus"></i>
            <div v-if="isEdit && fileLists.length === 0" slot="tip" class="el-upload__tip u-ml10 u-text">
              比例：16：9
              <br />
              格式：jpg.png.pneg.gif
            </div>
          </el-upload>
          <!-- <img v-else :src="fileLists[0]?.url" style="width: 146px; height: 146px" /> -->
        </el-form-item>
      </el-col>
      <el-col :span="10">
        <el-form-item label="机构名称" prop="enterpriseName">
          <el-input
            v-filter-input
            style="width: 15vw"
            v-model.trim="formParams.enterpriseName"
            placeholder="请输入机构名称"
            clearable
            size="small"
          />
        </el-form-item>
        <br />
        <el-form-item label="统一社会信用代码" prop="uscc">
          <el-input
            v-filter-input
            style="width: 15vw"
            v-model.trim="formParams.uscc"
            placeholder="请输入统一社会信用代码"
            clearable
            size="small"
          />
        </el-form-item>
        <br />
        <el-form-item label="机构组织代码" prop="enterpriseViewId">
          <el-input
            v-filter-input
            style="width: 15vw"
            v-model.trim="formParams.enterpriseViewId"
            placeholder="请输入机构组织代码"
            clearable
            size="small"
          />
        </el-form-item>
        <br />
        <el-form-item label="机构类型" prop="entrustType">
          <el-select
            class="el-input_search"
            v-model="formParams.entrustType"
            placeholder="请选择机构类型"
            clearable
            size="small"
            style="width: 15vw !important"
          >
            <el-option v-for="dict in dwlxLists" :key="dict.code" :label="dict.name" :value="dict.code" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-form-item>
    <br />
    <el-form-item label="机构介绍" prop="introduce">
      <el-input
        type="textarea"
        placeholder="请输入内容"
        v-model="formParams.introduce"
        maxlength="200"
        show-word-limit
        style="width: 55vw"
      ></el-input>
    </el-form-item>
    <el-form-item
      label="注册地址："
      :rules="{ required: isEdit ? true : false, message: '请输入注册地址', trigger: ['blur', 'change'] }"
    >
      <el-form-item prop="province">
        <el-select
          class="el-input_search"
          v-model="formParams.province"
          placeholder="请选择省"
          clearable
          size="small"
          style="width: 10vw !important"
          disabled
        >
          <el-option v-for="dict in provinceList" :key="dict.areaName" :label="dict.areaName" :value="dict.areaName" />
        </el-select>
      </el-form-item>
      <el-form-item prop="city">
        <el-select
          class="el-input_search"
          v-model="cityValue"
          value-key="areaCode"
          placeholder="请选择市"
          clearable
          size="small"
          style="width: 10vw !important"
          @change="citysChange"
        >
          <el-option v-for="dict in cityList" :key="dict.areaCode" :label="dict.areaName" :value="dict" />
        </el-select>
      </el-form-item>
      <el-form-item prop="county">
        <el-select
          class="el-input_search"
          v-model="formParams.county"
          placeholder="请选择县"
          clearable
          size="small"
          style="width: 10vw !important"
        >
          <el-option v-for="dict in countyList" :key="dict.areaCode" :label="dict.areaName" :value="dict.areaName" />
        </el-select>
      </el-form-item>
      <el-form-item prop="lon">
        <el-input
          v-filter-input
          oninput="value=value.replace(/[^0-9.]/g,'')"
          style="width: 10.4vw"
          v-model.trim="formParams.lon"
          placeholder="经度"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item prop="lat">
        <el-input
          v-filter-input
          oninput="value=value.replace(/[^0-9.]/g,'')"
          style="width: 10.4vw"
          v-model.trim="formParams.lat"
          placeholder="纬度"
          clearable
          size="small"
        />
      </el-form-item>
      <br />
      <el-form-item prop="address">
        <el-input
          v-filter-input
          style="width: 55vw"
          v-model.trim="formParams.address"
          placeholder="请输入详细地址"
          clearable
          size="small"
        />
      </el-form-item>
    </el-form-item>
    <br />
    <el-form-item prop="responsiblePerson" label="机构负责人" style="width: 39vw">
      <el-input
        v-filter-input
        v-model.trim="formParams.responsiblePerson"
        placeholder="请输入"
        clearable
        size="small"
        style="width: 15vw"
      />
    </el-form-item>
    <el-form-item prop="contactPhone" label="联系电话">
      <el-input
        v-filter-input
        v-model.trim="formParams.contactPhone"
        placeholder="请输入"
        clearable
        size="small"
        style="width: 15vw"
      />
    </el-form-item>
    <br />
    <el-form-item label="户号信息">
      <el-button
        v-if="isEdit"
        icon="el-icon-plus"
        size="small"
        type="primary"
        plain
        style="margin-bottom: 20px"
        @click="addMeter"
      >
        添加户号
      </el-button>
      <el-form
        class="u-mb20"
        ref="accountForm"
        v-for="(account, index) in formParams.gaugesList"
        :key="index"
        :model="account"
        :rules="accountRules"
        :disabled="!isEdit"
      >
        <el-form-item prop="gaugesName">
          <el-input
            v-filter-input
            style="width: 12vw; margin-right: 20px"
            v-model.trim="account.gaugesName"
            placeholder="请输入户号名称"
            clearable
            size="small"
            class="u-mb10"
          />
        </el-form-item>
        <el-form-item prop="gaugesNum">
          <el-input
            v-filter-input
            style="width: 40vw"
            v-model.trim="account.gaugesNum"
            placeholder="请输入户号编号"
            clearable
            size="small"
            class="u-mb10"
          />
        </el-form-item>
        <i v-if="isEdit" class="el-icon-circle-close cursor u-fs20" @click="deleteMeter(index)"></i>
      </el-form>
    </el-form-item>
  </el-form>
</template>
<style lang="scss" scoped>
.itemForm {
  :deep(> .el-form-item__content) {
    width: 100% !important;
  }
}
.uploadPic {
  display: flex;
  align-items: flex-end;
}
.uploadPic ::v-deep(.el-upload--picture-card) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 363px;
  height: 204px;
}
.styleA ::v-deep(.el-upload--picture-card) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 363px;
  height: 204px;
}
.styleB ::v-deep(.el-upload--picture-card) {
  display: none;
}
.uploadPic ::v-deep(.el-upload-list__item) {
  width: 363px;
  height: 204px;
}
.queryForm ::v-deep(.el-textarea__inner) {
  height: 80px;
  // width: 750px;
}
.app-dark .queryForm ::v-deep(.el-textarea__inner) {
  background: rgba(0, 0, 0, 0.5);
  border: 1px solid #262f48;
}
</style>
